#include <iostream>
#include <boost/thread/thread.hpp>

#include <AppView.hpp>

#include "EventDispatcher.h"
#include "AppLoader.h"
#include "../View/graphicEngine.h"
#include "../Model/System.h"
#include "../Model/AppList.h"
#include "../Model/User.h"
#include "../Model/SystemPreferences.h"


AppLoader* appLoader;
System* sys;
GraphicEngine* ge;
EventDispatcher* eventDispatcher;

void eventObserver() {
  eventDispatcher->startObserver();
}

int main(int argc, char *argv[]) {

  System* tmp = new System();
  tmp->saveConfiguration("conf/default.conf");


  appLoader = new AppLoader("app");
  App* app1 = appLoader->loadApp("AppFlickR");
  App* app2 = appLoader->loadApp("AppFlickR");
  App* app3 = appLoader->loadApp("AppWeather");

  AppList appList;

  appList.addApp(app1);
  appList.addApp(app2);
  appList.addApp(app3);
  appList.addApp(app3);
  //appList.addApp(app5);

  try {
    /* initialize the system and load preferences */
    sys = System::SystemFactory("conf/default.conf");
  } catch (boost::archive::archive_exception e) {
    std::cerr << "Error while reading your configuration file preferences"
        << std::endl << "Check if your conf/default.conf is correct"
        << std::endl;
    delete sys;
  }

  /* initialize graphic engine before registering callbacks */
  ge = new GraphicEngine(sys->getPreferences(), &appList, &argc, argv);
  eventDispatcher = new EventDispatcher(sys, ge, &appList);

  /* start the system */
  boost::thread eventObs(&eventObserver);
  ge->start();

  eventObs.join();

  delete eventDispatcher;
  delete ge;
  delete sys;
  delete appLoader;

  return 0;
}
